package com.chen.q1.initial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyHttpServer extends Thread {
    private final  int port;
    private final  String proxiedServer;

    static int MAXIN = 32 * 1024;
    static int MAXOUT = 32 * 1024;

    static EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    static EventLoopGroup workGroup = new NioEventLoopGroup(16);

    public NettyHttpServer(int port, String proxiedServer) {
        this.port = port;
        this.proxiedServer = proxiedServer;
    }

    @Override
    public void run() {
        try{
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childOption(ChannelOption.SO_REUSEADDR,true)
                    .childOption(ChannelOption.SO_RCVBUF,MAXIN)
                    .childOption(ChannelOption.SO_SNDBUF,MAXOUT)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            sb.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new HttpInitializer(proxiedServer));

            Channel ch = sb.bind(port).sync().channel();
            System.out.println("开启netty http服务，监听地址为http://127.0.0.1:"+port);
            ch.closeFuture().sync();
        } catch(InterruptedException e ){
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
